'use strict';
const db = uniCloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    // 获取请求参数
    const { page = 1, pageSize = 20, keyword = '' } = event;
    const { OPENID } = context;
    
    // 验证管理员权限
    const adminInfo = await db.collection('admin_users')
      .where({
        openid: OPENID,
        is_active: true
      })
      .field({
        _id: 1,
        username: 1,
        role: 1
      })
      .get();
    
    // if (adminInfo.data.length === 0) {
    //   return {
    //     code: 403,
    //     message: '您没有管理员权限'
    //   };
    // }
    
    // 构建查询条件
    const query = {};
    if (keyword) {
      query.$or = [
        { _id: keyword },
        { username: db.RegExp({
          regexp: keyword,
          options: 'i'
        }) }
      ];
    }
    
    // 计算分页参数
    const skip = (page - 1) * pageSize;
    
    // 执行查询
    const usersResult = await db.collection('users')
      .where(query)
      .skip(skip)
      .limit(pageSize)
      .orderBy('create_time', 'desc')
      .get();
    
    // 为每个用户获取统计信息
    const usersWithStats = await Promise.all(usersResult.data.map(async (user) => {
      // 统计收藏数量
      const collectionCount = await db.collection('collections')
        .where({ user_id: user._id })
        .count();
      
      // 统计下载数量
      const downloadCount = await db.collection('downloads')
        .where({ user_id: user._id })
        .count();
      
      // 统计反馈数量
      const feedbackCount = await db.collection('feedbacks')
        .where({ user_id: user._id })
        .count();
      
      return {
        ...user,
        collection_count: collectionCount.total,
        download_count: downloadCount.total,
        feedback_count: feedbackCount.total
      };
    }));
    
    // 记录操作日志
    await db.collection('admin_logs').add({
      admin_id: adminInfo.data[0]._id,
      admin_name: adminInfo.data[0].username,
      action: 'get_users',
      query: { page, pageSize, keyword },
      count: usersWithStats.length,
      create_time: Date.now()
    });
    
    return {
      code: 0,
      message: '获取用户列表成功',
      data: usersWithStats
    };
    
  } catch (error) {
    console.error('获取用户列表失败:', error);
    return {
      code: 500,
      message: '获取用户列表失败，请稍后重试',
      error: error.message
    };
  }
};